package com.example.demo2.controller;

import com.example.demo2.entity.Feedback;
import com.example.demo2.mapper.FeedbackMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RestController
@CrossOrigin
public class FeedbackController {
    @Autowired
    FeedbackMapper feedbackMapper;

    private ConcurrentHashMap<String, Integer> concurrentMap;

    @Autowired
    public void MyController(ConcurrentHashMap<String, Integer> concurrentMap) {
        this.concurrentMap = concurrentMap;
    }

    @PostMapping("/insertFeedback")
    public ResponseEntity<?> insertFeedback(@RequestBody String feedback) {
        try {
            // 调用服务层方法保存反馈
            Integer uID = (Integer) concurrentMap.get("uID");
            if(uID==null) {
            }
            else
            {
                Feedback feedback1=new Feedback();
                Date now = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String backTime = dateFormat.format(now);
                feedback1.setDetectorId(uID);
                feedback1.setBackTime(backTime);
                feedback1.setFeedback(feedback);
                feedbackMapper.insertFeedback(feedback1);
            }
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("留言提交失败");
        }
    }


    @GetMapping("/getuID")
    public Integer getuId(){
        return (Integer) concurrentMap.get("uID");
    }

    @RequestMapping("/getAllFeedback")
    public List<Feedback> getAllFeedback()
    {
        List<Feedback> feedbacks = feedbackMapper.getAllfeedback();

        for(Feedback feedback : feedbacks)
        {
            int detecId = feedback.getDetectorId();
            int responId=feedback.getSponsorId();

            feedback.setDetectorName(feedbackMapper.finduRealNameById(detecId));
            feedback.setSponsorName(feedbackMapper.finduRealNameById(responId));
        }

        return feedbacks;
    }

    @PatchMapping("/addResponse")
    public int addResponse(@RequestBody Feedback feedback)//int spoid, String response, String restime, int backid
    {
        int spoid = feedback.getSponsorId();
        int backid = feedback.getBackId();
        String response = feedback.getResponse();
        String restime = feedback.getResTime();

        return feedbackMapper.addResponse(spoid,response,restime,backid);
    }

    @RequestMapping("/getBackAndSpo")
    public Feedback findBackAndSpoById(@RequestParam int backId)
    {
        Feedback feedback = feedbackMapper.findBackAndSpoById(backId);
        return feedback;
    }


    @PostMapping("/submitResponse")
    public ResponseEntity<Map<String, Object>> submitResponse(@RequestBody Map<String, Object> payload) {
        System.out.println("Received payload: " + payload); // 调试日志

        Integer backId = null;
        String responseContent = null;

        // 从 payload 中获取参数
        try {
            backId = (Integer) payload.get("backId");
            responseContent = (String) payload.get("response");
        } catch (ClassCastException e) {
            System.err.println("参数类型错误: " + e.getMessage());
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "参数类型错误"));
        }

        if (backId == null || responseContent == null) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "参数不完整"));
        }

        // 设置 spoid 为 1
        int spoid = 1;

        // 获取当前时间
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        int result = feedbackMapper.addResponse(spoid, responseContent, currentTime, backId);
        if (result > 0) {
            return ResponseEntity.ok(Map.of("success", true, "message", "回复提交成功"));
        } else {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "回复提交失败"));
        }
    }

    @GetMapping("/findAllFeedback")
    public List<Feedback> findAllFeedback() {
        Integer uID = (Integer) concurrentMap.get("uID");
        if(uID==null) {
            return null;
        }
        return feedbackMapper.getFeedback(uID);
    }
}
